package com.aco.fatureapp.activity;

import java.util.HashSet;
import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.aco.fatureapp.R;
import com.aco.fatureapp.auxiliary.DeviceAdapter;
import com.aco.fatureapp.auxiliary.DeviceItem;
import com.aco.fatureapp.model.Printer;
import com.aco.fatureapp.utilitary.Utils;

public class DeviceListActivity extends ListActivity {

	public static final String VALUE_RETURN = "DeviceListActivity.valueReturn";

	private Set<BluetoothDevice> mAvailableDevices = new HashSet<BluetoothDevice>();

	private Set<BluetoothDevice> mPairedDevices;
	private DeviceAdapter mAdapter;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		Utils.startBluetooth(this);

		getListView().setPadding(20, 0, 20, 20);

		mAdapter = new DeviceAdapter(this);

		mPairedDevices = BluetoothAdapter.getDefaultAdapter()
				.getBondedDevices();

		setPairedDevices();
		setListAdapter(mAdapter);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(final android.view.Menu menu) {
		super.onCreateOptionsMenu(menu);

		final MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.action_bar_menu_device, menu);

		getActionBar().setDisplayHomeAsUpEnabled(true);

		return true;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home: {
			finish();
			return true;
		}
		case R.id.menu_refresh: {
			mAdapter.clear();
			mAvailableDevices.clear();

			setPairedDevices();
			setAvailableDevices(DeviceAdapter.SHOW_PROGRESS, false);
			discoverDevices();
			return true;
		}
		case R.id.menu_cancelar: {
			finish();
			return true;
		}
		}

		return true;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);

		Intent data = new Intent();

		DeviceItem item = (DeviceItem) getListAdapter().getItem(position);

		String[] printerSelected = item.getTitle().split("\n");

		Printer printer = new Printer();
		printer.name = printerSelected[0];
		printer.mac = printerSelected[1];

		data.putExtra(VALUE_RETURN, printer);

		setResult(PrinterActivity.SELECT_DEVICE, data);
		finish();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.ListActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		try {
			if (mReceiver != null) {
				unregisterReceiver(mReceiver);
			}
		}
		catch (IllegalArgumentException e) {
			// receiver isn't registered.
		}

		super.onDestroy();
	}

	/**
	 * Preenche a lista de dispositivos pareados.
	 */
	private void setPairedDevices() {
		mAdapter.addSectionHeaderItem("Dispositivos Pareados",
				DeviceAdapter.HIDE_PROGRESS);

		if (mPairedDevices.size() > 0) {

			for (BluetoothDevice device : mPairedDevices) {
				mAdapter.addItem(device.getName() + "\n" + device.getAddress(),
						device.getBluetoothClass(), DeviceAdapter.CLICKABLE);
			}
		}
		else {
			mAdapter.addItem("Nenhum dispositivo pareado.", null,
					DeviceAdapter.NOT_CLICKABLE);
		}
	}

	/**
	 * Preenche a lista de dispositivos pareados.
	 */
	private void setAvailableDevices(final boolean showProgress,
			final boolean finished) {

		if (mAvailableDevices.size() > 0) {

			mAdapter.addSectionHeaderItem("Dispositivos Disponíveis",
					showProgress);

			for (BluetoothDevice device : mAvailableDevices) {
				mAdapter.addItem(device.getName() + "\n" + device.getAddress(),
						device.getBluetoothClass(), DeviceAdapter.CLICKABLE);
			}
		}
		else {
			mAdapter.addSectionHeaderItem("Dispositivos Disponíveis",
					showProgress);

			if (finished) {
				mAdapter.addItem("Nenhum dispositivo encontrado.", null,
						DeviceAdapter.NOT_CLICKABLE);
			}
		}
	}

	/**
	 * Realiza uma busca por dispositivos ainda não pareados.
	 */
	private void discoverDevices() {
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);

		BluetoothAdapter.getDefaultAdapter().startDiscovery();
	}

	/**
	 * Callback para tratar a resposta do processo de descoberta dos
	 * dispositivos bluetooth.
	 */
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

				mAvailableDevices.add(device);
			}
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				mAdapter.clear();
				setPairedDevices();
				setAvailableDevices(DeviceAdapter.HIDE_PROGRESS, true);
				setListAdapter(mAdapter);
			}
		}
	};
}